﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using TSharp.Core.Util.Properties;

namespace TSharp.Core.Util.Numeric
{
    /// <summary>
    /// 
    /// </summary>
    /// <author>
    /// tangjingbo
    /// </author>
    /// <remarks>
    /// tangj15 at 2012-6-26 16:45
    /// </remarks>
    public static class HexCodec
    { 
        /// <summary>
        /// Gets the bytes.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static byte[] GetBytes(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            if ((value.Length % 2) != 0)
            {
                throw new FormatException(Resources.OddCharacterCount);
            }
            byte[] buffer = new byte[value.Length / 2];
            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = byte.Parse(value.Substring(i * 2, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture);
            }
            return buffer;
        }

        /// <summary>
        /// Gets the string.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public static string GetString(byte[] value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            StringBuilder builder = new StringBuilder(value.Length * 2);
            foreach (byte num in value)
            {
                builder.Append(num.ToString("x2", CultureInfo.InvariantCulture));
            }
            return builder.ToString();
        }
    }
}
